// import store from "@/store";
import config from "@/config";
import { getAccessToken, setToken, getRefreshToken } from "@/utils/auth";
import errorCode from "@/utils/errorCode";
import { toast, showConfirm, tansParams } from "@/utils/common";
// open -na "Google Chrome" --args --disable-web-security --user-data-dir="/tmp/chrome_dev_session"
let timeout = 10000;
const baseUrl = config.baseUrl + config.baseApi;
// 是否正在刷新中
let isRefreshToken = false;
let requestList = [];
const request = (config) => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false;
  config.header = config.header || {};
  if (getAccessToken() && !isToken) {
    config.header["Auth-Token"] = getAccessToken();

    // ab2c39c185294886914f0ed740d90246
  }
  //  if(!isToken){
  // config.header["Authorization"] = "Bearer 2f8eb146b9a44c82a37c52ebac57dbae";
  //  }
  // config.header["Authorization"] = "Bearer 0d20b6b4558540f4822e01416219dc37"
  // 设置租户 TODO 芋艿：强制 1 先
  config.header["tenant-id"] = "1";
  // get请求映射params参数
  // if (config.params) {
  //   let url = config.url + "?" + tansParams(config.params);
  //   url = url.slice(0, -1);
  //   config.url = url;
  // }
  return new Promise((resolve, reject) => {
    uni
      .request({
        method: config.method || "get",
        timeout: config.timeout || timeout,
        url: config.baseUrl || baseUrl + config.url,
        data: config.data || config.params || {},
        // header: config.header,
        header: config.header,
        dataType: "json",
      })
      .then(async (res) => {
        // console.log(response);
        // let [error, res] = response;
        // if (error) {
        // 	toast("后端接口连接异常");
        // 	reject("后端接口连接异常");
        // 	return;
        // }
        const code = res.data.code || 200;
        const msg = errorCode[code] || res.data.msg || errorCode["default"];

        if (code === 401) {
          reject("无效的会话，或者会话已过期，请重新登录。");
          return handleAuthorized();

          // 如果未认证，并且未进行刷新令牌，说明可能是访问令牌过期了
          if (!isRefreshToken) {
            isRefreshToken = true;
            // 1. 如果获取不到刷新令牌，则只能执行登出操作

            try {
              const refreshTokenRes = await refreshToken();

              // 2.1 刷新成功，则回放队列的请求 + 当前请求
              setToken(refreshTokenRes.data);
              // config.headers.Authorization = "Bearer " + getAccessToken();

              requestList.forEach((cb) => {
                cb();
              });
              requestList = [];
              let data = await request(config);
              return resolve(data);
            } catch (e) {
              // 为什么需要 catch 异常呢？刷新失败时，请求因为 Promise.reject 触发异常。
              // 2.2 刷新失败，只回放队列的请求
              requestList.forEach((cb) => {
                cb();
              });
              // 提示是否要登出。即不回放当前请求！不然会形成递归
              reject("无效的会话，或者会话已过期，请重新登录。");
              return handleAuthorized();
            } finally {
              requestList = [];
              isRefreshToken = false;
            }
          } else {
            // 添加到队列，等待刷新获取到新的令牌
            return new Promise((resolve) => {
              requestList.push(() => {
                config.headers.Authorization = "Bearer " + getAccessToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
                resolve(request(config));
              });
            });
          }
        } else if (code === 500) {
          toast(msg);
          reject("500");
        } else if (code !== 200 && code !== 0) {
          toast(msg);
          reject(code);
        }
        resolve(res.data);
      })
      .catch((error) => {
        let { message } = error;
        if (message === "Network Error") {
          message = "服务器连接异常";
        } else if (message.includes("timeout")) {
          message = "系统接口请求超时";
        } else if (message.includes("Request failed with status code")) {
          message = "系统接口" + message.substr(message.length - 3) + "异常";
        }
        toast(message);
        reject(error);
      });
  });
};
const refreshToken = async () => {
  return await request({
    url: `/system/auth/refresh-token?refreshToken=` + getRefreshToken(),
    method: "POST",
  });
};
const handleAuthorized = () => {
  showConfirm("登录状态已过期，您可以继续留在该页面，或者重新登录?").then(
    (res) => {
      if (res.confirm) {
        // store.dispatch("LogOut").then((res) => {
        uni.reLaunch({
          url: "/pages/login/login",
        });
        // });
      }
    }
  );
};
export default request;
